<?php
/**
 * 字段逻辑层
 * @author maniac
 */
namespace app\common\logic;

use think\Db;
use app\common\model\Fields AS FieldsModel;
use app\common\model\Tables;

class Fields extends Base
{    
    /**
     * 添加/编辑
     * @param array $data 请求的数据
     */
    public function save($data)
    {
        if (isset($data['id']) && $data['id']) {
            // 编辑时，先获取数据表原字段
            $temp = FieldsModel::field('f,fname,is_diy')->where('id', $data['id'])->find();
            if (!$temp['is_diy']) {
                exception('系统字段无法编辑');
            }
            $data['origin_f']     = $temp['f'];
            $data['origin_fname'] = $temp['fname'];
        }
        // 数据字段类型
        $ftype = config('ftype.ftype');
        if (!isset($data['flen']) || !trim($data['flen'])) {
            $data['flen'] = $ftype[$data['ftype']]['len'];
        } elseif ($data['flen'] > $ftype[$data['ftype']]['len']) {
            $data['flen'] = $ftype[$data['ftype']]['len'];
        } else {
            $data['flen'] = (int)$data['flen'];
        }
        if (strpos($data['ftype'], 'TEXT') !== false) {
            $data['flen'] = 0;
        }
        
        $result = parent::save($data);
        if ($result !== false) {
            $this->editField($data);
            if ($result === true) {
                // 编辑时，更新表单录入项
                $this->updateEnterForm($data);
            }
        }
        return $result;
    }
    
    /**
     * 批量排序
     * @param  array $data 请求的信息
     */
    public function listOrder($data)
    {
        $result = parent::listOrder($data);
        if ($result) {
            $this->updateEnterForm($data);
        }
        return $result;
    }
    
    /**
     * 编辑数据表字段
     * @param  array $data 请求的信息
     */
    private function editField($data)
    {
        $flen    = "({$data['flen']})";
        $isNull  = ' NOT NULL';
        $default = " DEFAULT ''";
        
        if (strpos($data['ftype'], 'INT') !== false || $data['ftype'] == 'FLOAT' || $data['ftype'] == 'DOUBLE') {
            $default = " DEFAULT 0";
        } elseif (strpos($data['ftype'], 'TEXT') !== false) {
            $flen = '';
        }
        
        if (isset($data['id']) && $data['id']) {
            // 编辑
            return Db::execute("ALTER TABLE `".config('database.prefix')."{$data['tbname']}` CHANGE `{$data['origin_f']}` `{$data['f']}` {$data['ftype']}{$flen}{$isNull}{$default} COMMENT '{$data['ftext']}'");
        } else {
            // 添加
            return Db::execute("ALTER TABLE `".config('database.prefix')."{$data['tbname']}` ADD `{$data['f']}` {$data['ftype']}{$flen}{$isNull}{$default} COMMENT '{$data['ftext']}'");
        }
    }
    
    /**
     * 更新表单录入项
     * @param  array $data 请求的信息
     */
    private function updateEnterForm($data)
    {
        // 获取字段对应模型
        $map    = config('db_map.');
        // 查询是否是 cms 的数据表，如果是添加 contents 内容数据表。
        $mod    = Tables::field('id')->where('tbname', $data['tbname'])->find();
        $tbname = '';
        if ($mod) {
            $model  = 'app\common\model\Mods';
            $tbname = 'contents,'.$data['tbname'];
        } else {
            $model  = 'app\common\model\\'.$map[$data['tbname']]['form'];
            $tbname = $data['tbname'];
        }
        
        // 查询数据表下所有字段
        $fields = FieldsModel::field('id')->where('tbname', 'in', $tbname)->order('list_order DESC,id ASC')->select();
        
        // 查询所有模型
        $rows   = $model::field(true)->order('id ASC')->select();
        if ($rows) {
            $rows = $rows->toArray();
            $update = [];
            foreach ($rows as $row) {
                $set['id'] = $row['id'];
                // 字段名称
                if (isset($data['fname']) && $data['fname']) {
                    foreach ($row['field'] as $k => $v) {
                        // 如果当前模型的字段名称等于修改之前的字段名称，则更新字段名称。
                        if ($v === $data['origin_fname']) {
                            $row['field'][$k] = $data['fname'];
                        }
                    }
                    $set['field'] = serialize($row['field']);
                }
                
                // 录入项
                if (isset($row['enter'])) {
                    $temp = [];
                    foreach ($fields as $k => $v) {
                        if (in_array($v['id'], $row['enter'])) {
                            $temp[] = $v['id'];
                        }
                    }
                    $set['enter'] = serialize($temp);
                }
                
                // 前台录入项
                if (isset($row['qenter'])) {
                    $temp = [];
                    foreach ($fields as $k => $v) {
                        if (in_array($v['id'], $row['qenter'])) {
                            $temp[] = $v['id'];
                        }
                    }
                    $set['qenter'] = serialize($temp);
                }
                
                // 后台录入项
                if (isset($row['henter'])) {
                    $temp = [];
                    foreach ($fields as $k => $v) {
                        if (in_array($v['id'], $row['henter'])) {
                            $temp[] = $v['id'];
                        }
                    }
                    $set['henter'] = serialize($temp);
                }
                $update[]  = $set;
            }
            (new $model)->saveAll($update);
        }
    }
    
    /**
     * 获取模型
     */
    public function getModel()
    {
        return 'app\common\model\Fields';
    }
}
